#include "mysql.h"
/**
 * 初始化MySQL连接
 */
// MySQL连接句柄
MYSQL *conn;
void init_mysql() {
    conn = mysql_init(NULL);
    if (conn == NULL) {
        fprintf(stderr, "mysql_init() failed\n");
        exit(EXIT_FAILURE);
    }

    if (mysql_real_connect(conn, "localhost", "luanxiu", "123456", "qq_server", 0, NULL, 0) == NULL) {
        fprintf(stderr, "mysql_real_connect() failed\n");
        mysql_close(conn);
        exit(EXIT_FAILURE);
    }
}
/**
 * 关闭MySQL连接
 */
void close_mysql() {
    mysql_close(conn);
}
/**
 * 创建数据库和表
 */
void create_database_and_tables() {
    if (mysql_query(conn, "CREATE DATABASE IF NOT EXISTS qq_server")) {
        fprintf(stderr, "CREATE DATABASE error: %s\n", mysql_error(conn));
        return;
    }

    if (mysql_query(conn, "USE qq_server")) {
        fprintf(stderr, "USE DATABASE error: %s\n", mysql_error(conn));
        return;
    }

    const char *create_users_table =
        "CREATE TABLE IF NOT EXISTS users ("
        "user_id INT AUTO_INCREMENT PRIMARY KEY,"
        "username VARCHAR(255) UNIQUE NOT NULL,"
        "password VARCHAR(255) NOT NULL,"
        "status ENUM('offline', 'online') DEFAULT 'offline'"
        ")";
    
    if (mysql_query(conn, create_users_table)) {
        fprintf(stderr, "CREATE TABLE users error: %s\n", mysql_error(conn));
        return;
    }

    const char *create_friends_table =
        "CREATE TABLE IF NOT EXISTS friends ("
        "user_id INT,"
        "friend_id INT,"
        "status ENUM('pending', 'accepted'),"
        "PRIMARY KEY (user_id, friend_id)"
        ")";
    
    if (mysql_query(conn, create_friends_table)) {
        fprintf(stderr, "CREATE TABLE friends error: %s\n", mysql_error(conn));
        return;
    }

    const char *create_messages_table =
        "CREATE TABLE IF NOT EXISTS messages ("
        "message_id INT AUTO_INCREMENT PRIMARY KEY,"
        "sender_id INT,"
        "receiver_id INT,"
        "message TEXT,"
        "timestamp DATETIME DEFAULT CURRENT_TIMESTAMP"
        ")";
    
    if (mysql_query(conn, create_messages_table)) {
        fprintf(stderr, "CREATE TABLE messages error: %s\n", mysql_error(conn));
        return;
    }
}

/**
 * 插入测试用户
 */
void insert_test_user(const char *email,const char *username, const char *password) {
    char query[256];
    sprintf(query, "INSERT INTO users (username, password) VALUES ('%s', '%s')", username, password);
    if (mysql_query(conn, query)) {
        fprintf(stderr, "INSERT error: %s\n", mysql_error(conn));
    } else {
        printf("Test user inserted successfully.\n");
    }
}

